/**
 * 
 * 查询治疗记录
 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Tabs,
    DatePicker, Button, Steps, Icon, Divider, message, Modal, Tooltip
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import RangeDatePicker from 'components/rangePicker/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import ShowHistoryListModal from './component/ShowHistoryListModal';
import { Prompt } from 'react-router';
import store from 'store';
import moment from 'moment';
import './style/index.less';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;
const { Step } = Steps;
const { TextArea } = Input;

class MedicalRecordPage extends React.Component {
    constructor(props) {
        super(props)
        var recordData = JSON.parse(sessionStorage.getItem('recordData'));
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            recordData: recordData,
            patientData: patientData,
            userData: userData,
            isOpen: true
            // current: 0
        }
    }

    componentDidMount() {
        this.getAllSelect()
        this.initData()
        // this.loadData()
        this.loadAcographyPage()
        this.loadReservationRecordPage()
    }

    loadHospitalData() {
        var params = {
            params: [{
                ID: this.state.cureAppID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040169",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        hospList: res.result.dataArr,
                        totalPrice: res.result.totalPrice,
                        payPrice: res.result.unAmount,
                        unPayPrice: res.result.reAmount,
                    })
                }
            }
        });
    }

    loadBookRecord() {
        var params = {
            params: [{
                cureAppID: this.state.cureAppID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050169",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        orderList: res.result.data,
                        // totalPrice: res.result.totalPrice,
                        // payPrice: res.result.payPrice,
                        // unPayPrice: res.result.unPayPrice,
                    })
                }
            }
        });
    }

    initData() {
        let data = {
            params: [{
                compontName: "AppointTreatPage",
                type: "C",
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var columns = res.result.C;
                    var dynColumns = []
                    for (var i = 0; i < columns.length; i++) {
                        dynColumns.push({
                            title: columns[i].title,
                            dataIndex: columns[i].dataIndex,
                            width: parseInt(columns[i].width),
                            align: columns[i].align || 'center'
                        })
                    }
                    this.setState({
                        column: dynColumns,
                        appointWidth: res.totalWidth
                    })
                    this.props.hanlderThis.setState({
                        reload: false,
                    })
                }
            }
        })
    }

    loadReservationRecordPage() {
        let data = {
            params: [{
                compontName: "ReservationRecordPage",
                type: "C",
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var columns = res.result.C;
                    var dynColumns = []
                    for (var i = 0; i < columns.length; i++) {
                        dynColumns.push({
                            title: columns[i].title,
                            dataIndex: columns[i].dataIndex,
                            width: parseInt(columns[i].width),
                            align: columns[i].align || 'center'
                        })
                    }
                    this.setState({
                        recordColumn: dynColumns,
                        recordWidth: res.totalWidth
                    })
                    this.props.hanlderThis.setState({
                        reload: false,
                    })
                }
            }
        })
    }

    loadAcographyPage() {
        let data = {
            params: [{
                compontName: "AcographyPage",
                type: "C",
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var columns = res.result.C;
                    var dynColumns = []
                    for (var i = 0; i < columns.length; i++) {
                        dynColumns.push({
                            title: columns[i].title,
                            dataIndex: columns[i].dataIndex,
                            width: parseInt(columns[i].width),
                            align: columns[i].align || 'center'
                        })
                    }
                    this.setState({
                        appColumn: dynColumns,
                        appWidth: res.totalWidth
                    })
                    this.props.hanlderThis.setState({
                        reload: false,
                    })
                }
            }
        })
    }


    loadData() {
        var params = {
            params: [{
                admID: this.state.patientData.admID,
                dateFrom: this.state.StartDate,
                dateTo: this.state.EndDate,
                admID:this.state.adviceID,
                admYear:this.state.admYears
            }],
            // pagination: [{
            //     pageSize: this.state.pageSize,
            //     currentPage: page
            // }]
        }
        $http.post('urlDeault', this, {
            code: "03050165",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: !Util.isEmpty(res.result.data) ? res.result.data : [],
                        detailData: !Util.isEmpty(res.result.data) ? res.result.data[0] : '',
                        totalCount: res.result.totalCount,
                        cureAppID: !Util.isEmpty(res.result.data) ? res.result.data[0].cureAppID : '',
                    }, () => {
                        this.loadBookRecord()
                        this.loadHospitalData()
                        if (!Util.isEmpty(res.result.data)) {
                            // this.loadBookRecord()
                            this.loadApplicationDetail()
                        }
                    })
                }
            }
        });
    }

    getAllSelect() {
        let data = {}
        data = {
            params: [{
                patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
                admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
                admYearsFlag: "Y",//就诊年限
                orderTypeFlag: "Y",//医嘱类型
                admRecordFlag: "Y",//就诊记录
                orderStatusFlag: "Y",//医嘱状态
            }],
        }
        $http.post('urlS', this, {
            code: '03050130',
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    //thisTime
                    var adviceID = ''
                    var adviceTime = res.result.admRecord
                    if (!Util.isEmpty(adviceTime)) {
                        for (var i = 0; i < adviceTime.length; i++) {
                            if (adviceTime[i].thisTime == 'Y') {
                                adviceID = adviceTime[i].admID
                            }
                        }
                    }
                    this.setState({
                        yearArr: res.result.admYears,
                        adviceLogArr: res.result.admRecord,
                        typeArr: res.result.ordPriority,
                        statusArr: res.result.ordStatus,
                        admYears: res.result.admYears ? res.result.admYears[0].admYears : '',
                        adviceID: adviceID
                    },()=>{
                        this.loadData()
                    })
                }
            }
        })
    }

    //开始日期
    startChange(date) {
        this.setState({
            StartDate: date ? moment(date).format(dayFormat) : '',
        })
    }
    //结束日期
    endChange(date) {
        this.setState({
            EndDate: date ? moment(date).format(dayFormat) : '',
        })
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.cureAppID === this.state.cureAppID ? 'clickRowStyle' : '';
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    cureAppID: record.cureAppID,
                    detailData: record,
                    bookScheduleID: []
                }, () => {
                    this.loadApplicationDetail()
                    this.loadBookRecord()
                    this.loadHospitalData()
                })
            }
        };
    }
    loadApplicationDetail() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                cureAppID: this.state.cureAppID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040196",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        appDetail: res.result.data[0]
                    })
                }
            }
        });
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    onAcography = (ref) => {
        this.acography = ref;
    }
    onReservationRecord = (ref) => {
        this.reservationRecord = ref;
    }

    onHospClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    rowIds: record.ID,
                })
            }
        };
    }

    setHospRowClassName = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }

    onorderClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    bookScheduleID: record.bookScheduleID,
                })
            }
        };
    }

    setRoworderClassName = (record) => {
        return record.bookScheduleID === this.state.bookScheduleID ? 'clickRowStyle' : '';
    }

    handleCannelOrder() {
        if (Util.isEmpty(this.state.bookScheduleID)) {
            message.error('请选择您需要取消的预约数据',this.state.userData && this.state.userData.messageTime)
            return
        }
        var params = {
            params: [{
                userID: this.state.userData.userID,
                bookScheduleIDArr: [this.state.bookScheduleID]
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050170",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success('取消成功',this.state.userData && this.state.userData.messageTime)
                    this.setState({
                        bookScheduleID: []
                    }, () => {
                        this.loadBookRecord()
                    })
                }
            }
        });
    }

    //治疗预约单
    handleCanceOK() {
        this.setState({
            isShowHistoryListModal: true
        })
    }

    hideModal(name) {
        this.setState({
            [name]: false
        })
    }

    render() {
        const { collArr, yearArr, adviceLogArr, activeKey, typeArr, statusArr, columns, widthTotal } = this.state;

        //就诊年份
        var yearOption = []
        yearArr && yearArr.map((item, index) => {
            yearOption.push(<Option key={index} value={item.admYears}>{item.admYears}</Option>)
        })

        //就诊记录
        var adviceLogArrOption = []
        adviceLogArr && adviceLogArr.map((item, index) => {
            adviceLogArrOption.push(<Option key={index} value={item.admID}>
                {item.thisTime == "Y" ? <span style={{ color: "#1999db", marginRight: "4px" }}>本次</span> : ""}{item.admStr}</Option>)
        })

        return <div className='medical-record-body' style={{ width: '100%', height: '100%' }}>
            <ColumnAuthoritysModel
                clientWidth='800px'
                compontName="AppointTreatPage"
                configType="C"
                onRef={this.onColumnRef}
                reloadData={this.initData}
            />
            <ColumnAuthoritysModel
                clientWidth='800px'
                compontName="AcographyPage"
                configType="C"
                onRef={this.onAcography}
                reloadData={this.loadAcographyPage}
            />
            <ColumnAuthoritysModel
                clientWidth='800px'
                compontName="ReservationRecordPage"
                configType="C"
                onRef={this.onReservationRecord}
                reloadData={this.loadReservationRecordPage}
            />
            <ShowHistoryListModal isShow={this.state.isShowHistoryListModal}
                cureAppID={this.state.cureAppID}
                onHide={this.hideModal.bind(this, 'isShowHistoryListModal')}>
            </ShowHistoryListModal>
            <Card>
                <Card title={<span>申请列表</span>} style={{ width: '50%', float: 'left', height: '35vh' }}>
                    <Row>
                        <Col span={10}>
                            就诊年份：<Select style={{ width: '70%' }} placeholder='请选择年份' value={this.state.admYears}
                                onChange={Util.handleSelectChange.bind(this, 'admYears')}>{yearOption}</Select>
                        </Col>
                        <Col span={12}>
                            就诊记录：<Select style={{ width: '70%' }} placeholder='请选择就诊记录' value={this.state.adviceID}
                                onChange={Util.handleSelectChange.bind(this, 'adviceID')}>{adviceLogArrOption}</Select>
                        </Col>
                        <Col span={16} style={{ marginTop: 5 }}>
                            <RangeDatePicker isChange={true} format='YYYY-MM-DD' width={300} label={'申请日期：'}
                                startDate={this.state.StartDate} endDate={this.state.EndDate}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                        </Col>
                        <Col span={4} style={{ marginTop: 5 }}><Button type='primary' onClick={this.loadData.bind(this,'1')}>查询</Button></Col>
                    </Row>

                    <Table columns={this.state.column} style={{ marginTop: 5 }}
                        dataSource={this.state.dataSource}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                        bordered
                        rowKey={(data) => {
                            return data.cureAppID
                        }}
                        scroll={{ x: this.state.appointWidth, y: '18vh' }}
                        onHeaderRow={column => {
                            return {
                                onDoubleClick: () => {
                                    this.columnRef.onOpenModel();
                                },
                            };
                        }}
                        pagination={false}></Table>

                </Card>
                <Card title={<span>申请单详情</span>} style={{ width: '49.8%', float: 'right' }}>
                    <div>申请项目：<span>{this.state.appDetail && this.state.appDetail.appOrder}</span></div>
                    <div>
                        申请时间：<span>{this.state.appDetail && this.state.appDetail.applyTime}</span>
                        <span style={{ marginLeft: 10 }}>申请科室：<span>{this.state.appDetail && this.state.appDetail.appLoc}</span></span>
                        <span style={{ marginLeft: 10 }}>申请医生：<span>{this.state.appDetail && this.state.appDetail.appDoctor}</span></span>
                    </div>
                    <div>
                        治疗计划：<TextArea rows={4} value={this.state.appDetail && this.state.appDetail.appPlan} disabled={true} />
                        治疗目标：<TextArea rows={4} value={this.state.appDetail && this.state.appDetail.note} disabled={true} />
                    </div>
                </Card>
            </Card>

            <Card style={{ marginTop: 5 }}>
                <Tabs type="card" size='small'>
                    <TabPane tab="治疗记录" key="1">
                        <Table columns={this.state.appColumn} className='appoint-treat-table-body'
                            dataSource={this.state.hospList}
                            onRow={this.onHospClickRow}
                            rowClassName={this.setHospRowClassName}
                            bordered
                            rowKey={(data) => {
                                return data.ID
                            }}
                            title={() => {
                                return <div style={{ display: 'flex' }}>
                                    <div style={{ width: '95%' }}></div>
                                    <div><Button size='small' onClick={this.handleCanceOK.bind(this)}
                                        disabled={Util.isEmpty(this.state.hospList)}>治疗记录单</Button></div>
                                </div>
                            }}
                            scroll={{ x: this.state.appWidth, y: '18vh' }}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.acography.onOpenModel();
                                    },
                                };
                            }}
                            pagination={false}></Table>
                    </TabPane>
                    <TabPane tab="预约记录" key="2">
                        <Table columns={this.state.recordColumn} className='appoint-treat-table-body'
                            dataSource={this.state.orderList}
                            onRow={this.onorderClickRow}
                            rowClassName={this.setRoworderClassName}
                            bordered
                            rowKey={(data) => {
                                return data.bookScheduleID
                            }}
                            title={() => {
                                return <div style={{ textAlign: 'right' }}><Button type='primary' size='small'
                                    onClick={this.handleCannelOrder.bind(this)}>取消预约</Button></div>
                            }}
                            scroll={{ x: this.state.recordWidth, y: '18vh' }}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.reservationRecord.onOpenModel();
                                    },
                                };
                            }}
                            pagination={false}></Table>
                    </TabPane>
                </Tabs>
            </Card>
        </div>
    }

}
export default MedicalRecordPage;